<?php
/**
 * Bestselling products block
 *
 * @category   TinDat
 * @package    TinDat_Bnm
 * @author     Magento Oursourcing Team <info@magento-outsourcing.com>
 */ 
class TinDat_Bnm_Block_Bestsellingproductpage extends Mage_Catalog_Block_Product_Abstract
{
	/**
     * Retrive Bestselling product
     *
     * @param   
     * @Return Mage_Catalog_Block_Product_Bestseller
     */ 
	public function _prepareLayout() 
	{
		$categoryId=$this->getRequest()->getParam('cat_id');
		$storeId = Mage::app()->getStore()->getId();
		$value=$this->getRequest()->getParam('value');
		if($value==NULL || $value==0){
			if(isset($categoryId)) {
				$category=Mage::getModel('catalog/category')->load($categoryId);
				$products = Mage::getResourceModel('reports/product_collection')
					->addOrderedQty()
					->addAttributeToSelect('*') //Need this so products show up correctly in product listing
					->setStoreId($storeId)
					->addStoreFilter($storeId)
					->addAttributeToFilter('status','1')
					->addCategoryFilter($category);
					//->addAttributeToFilter('category_ids',$categoryId);
					//->printLogQuery(true);
			
			}
			else {
				$products = Mage::getResourceModel('reports/product_collection')
					->addOrderedQty()
					->addAttributeToSelect('*') //Need this so products show up correctly in product listing
					->setStoreId($storeId)
					->addStoreFilter($storeId)
					->addAttributeToFilter('status','1');
			}
		}
		else {	
			$lastMonth = date('Y-m-d h:i:s',mktime(0, 0, 0, date("m")-1, date("d"),   date("Y")));
			$lastSixMonth=date('Y-m-d h:i:s',mktime(0, 0, 0, date("m")-6, date("d"),   date("Y")));
			$lastYear  = date('Y-m-d h:i:s',mktime(0, 0, 0, date("m"),   date("d"),   date("Y")-1));
			if($value==1){
				$from=$lastMonth;
			}
			else if($value==2){
				$from=$lastSixMonth;
			}
			else if($value==3){
				$from=$lastYear;
			}
			if(isset($categoryId)) {
				$category=Mage::getModel('catalog/category')->load($categoryId);
				$products = Mage::getResourceModel('reports/product_collection')
            	->addOrderedQty($from,date('Y-m-d h:i:s'))
            	->addAttributeToSelect('*')
            	->setStoreId($storeId)
            	->addStoreFilter($storeId)
				->addCategoryFilter($category)
           		->addAttributeToFilter('status','1');
				//->printLogQuery(true);
			}
			else {
        	$products = Mage::getResourceModel('reports/product_collection')
            	->addOrderedQty($from,date('Y-m-d h:i:s'))
            	->addAttributeToSelect('*')
            	->setStoreId($storeId)
            	->addStoreFilter($storeId)
            	->addAttributeToFilter('status','1');
			//->printLogQuery(true);
			}
		}

	Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($products);
	//Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($products);
	
		
	$productIds = array();
	foreach($products as $key => $prod) { 		
		
		$parentId = $this->getParentId($prod);
		
		if($parentId == '') continue; 
		
		if($parentId == $prod->getId()) {
			$product = $prod;
		}
		else {
			$product = Mage::getModel('catalog/product')->setStoreId($storeId)->load($parentId);
		}
		
		/**
		 * if the product is not visible or is disabled
		 * OR,
		 * if two or more simple products of the same configurable product are ordered
		 */		
		if(!$product->isVisibleInCatalog() || in_array($product->getId(),$productIds)) continue; 
		
		$productIds[] = $product->getId();		
	}	
	
	//echo "<pre>"; print_r($productIds); exit;
	
	$products = Mage::getResourceModel('catalog/product_collection')->addIdFilter($productIds);	
	
	$this->setToolbar($this->getLayout()->createBlock('catalog/product_list_toolbar', 'Toolbar'));
	$toolbar = $this->getToolbar();

	$toolbar->setAvailableOrders(array(
	'ordered_qty'  => $this->__('Most Purchased'),
	'name'      => $this->__('Name'),
	'price'     => $this->__('Price')
	
		))
	->setDefaultOrder('ordered_qty')
	->setDefaultDirection('desc')
	->setCollection($products);
	return $this;
	}


	/**
     * Retrive Bestselling product collection
     *
     * @param   
     * @Return Mage_Reports_Model_Mysql4_Product_Collection
     */ 
	protected function _getProductCollection() {
		return $this->getToolbar()->getCollection();
	}

	/**
     * Retrive Toolbar
     *
     * @param   
     * @Return String (HTML for Toolbar)
     */ 
	public function getToolbarHtml() {
		return $this->getToolbar()->_toHtml();
	}

	/**
     * Retrive Mode
     *
     * @param   
     * @Return String (grid || list)
     */ 
	public function getMode() {
		return $this->getToolbar()->getCurrentMode();
	}

	/**
     * Retrive Loaded product Collection
     *
     * @param   
     * @Return Mage_Reports_Model_Mysql4_Product_Collection
     */ 
	public function getLoadedProductCollection() {
		return $this->_getProductCollection();
	}
	
	public function getAllCategory()
	{				
		return Mage::helper('catalog/category')->getStoreCategories('name', true, false);		
	}
	
	public function getParentId($product)
	{
		$parentId = '';
				
		// if the product visibility is not set to "Nowhere"
		// i.e. if the product is visible
		if($product->getVisibility() != '1') {
			$parentId = $product->getId(); 
			
			/* $parentIdArray = $product->loadParentProductIds()->getData('parent_product_ids');
			echo $product->getId(); 
			print_r($parentIdArray); 
			echo "***********<br/>"; */
		}		
		else {
			// get parent id if the product is not visible
			// this means that the product is associated with a configurable product
			$parentIdArray = $product->loadParentProductIds()->getData('parent_product_ids');
			
			/* echo $product->getId(); 
			print_r($parentIdArray); 
			echo "***********<br/>"; */
			
			if(!empty($parentIdArray)) {
				$parentId = $parentIdArray[0];
			}
		}		
		return $parentId; 
	}

} 


